﻿#region 程序集引用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Mvc;
#endregion

#region 版权注释
/*===========================================================================
// Copyright (C) 2017 Zhang.cn，并保留所有 
// 作者：吴岸标 QQ:405403610
// 创建日期：2017-09-03
// 功能描述： 把枚举转换成SelectListItem
===========================================================================*/
#endregion

namespace Zhang.Utils
{
    /// <summary>
    /// 把枚举转换成SelectListItem
    /// </summary>
    public class EnumExt
    {
        /// <summary>
        /// 获取枚举成员的自定义Attribute的一个属性值
        /// </summary>
        /// <param name="e">枚举成员</param>
        /// <returns></returns>
        public static string GetEnumDescription(object e)
        {
            //获取枚举成员的Type对象
            Type t = e.GetType();
            //获取Type对象的所有字段
            FieldInfo[] ms = t.GetFields();
            //遍历所有字段
            foreach (FieldInfo f in ms)
            {
                if (f.Name != e.ToString())
                {
                    continue;
                }
                if (f.IsDefined(typeof(EnumDisplayNameAttribute), true))
                {
                    return (f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), true)[0] as EnumDisplayNameAttribute).DisplayName;
                }
            }
            return e.ToString();
        }
        public static List<SelectListItem> GetSelectList(Type enumType)
        {
            List<SelectListItem> selectList = new List<SelectListItem>();
            //selectList.Add(new SelectListItem { Text = "--请选择--", Value = "",Selected = true});
            foreach (object e in Enum.GetValues(enumType))
            {
                selectList.Add(new SelectListItem { Text = GetEnumDescription(e), Value = ((int)e).ToString() });
            }
            return selectList;
        }

        /// <summary>
        /// 自定义特性
        /// </summary>
        public class EnumDisplayNameAttribute : Attribute
        {
            private string _displayName;
            public EnumDisplayNameAttribute(string displayName)
            {
                _displayName = displayName;
            }
            public string DisplayName
            {
                get
                {
                    return _displayName;
                }
            }
        }

        /// <summary>
        /// 将枚举类型项转变为字典
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <returns></returns>
        public static Dictionary<string, int> ToDictionary(Type enumType)
        {
            Dictionary<string, int> dicItems;

            dicItems = new Dictionary<string, int>();

            foreach (var e in Enum.GetValues(enumType))
            {
                dicItems.Add(GetEnumDescription(e), Convert.ToInt32(e));
            }

            return dicItems;
        }

      
    }
}
